import SearchForm from '@/components/searchform';
import { UserColumn } from '@/components/popovercolumn';
import { getCodeLocaleName } from '@/utils/codelist';
import {
  BLOCK_HEADER_HEIGHT,
  commonText,
  MODAL_FOOTER_HEIGHT,
  MODAL_HEADER_HEIGHT,
  MODAL_PADDING_HEIGHT,
} from '@/utils/utils';
import { Grid, Header } from 'gantd';
import { map } from 'lodash';
import type { ReactNode } from 'react';
import React, { forwardRef, useCallback, useEffect, useMemo, useState } from 'react';
import { connect } from 'umi';
import { columns, searchFormschema, searchUISchema } from './schema';

interface SelectorPanelProps {
  title?: string | ReactNode;
  visible?: boolean;
  onChange?: (rowKeys: string[], rows: any[]) => void;
  onCancel?: () => void;
  onOk?: (selectedRowKeys: string[], selectedRows: object[]) => void;
  ref?: any;
  [propName: string]: any;
}

const SelectorView = forwardRef((props: SelectorPanelProps, ref: any) => {
  const {
    userId,
    loading,
    visible,
    value,
    multiple,
    modalHei,
    tableHei,
    valueProp,
    selectedRowKeys,
    selectedRows,
    onChange,
    setSelectedItem,
    dispatch,
    withAuth,
    listUsers4selector,
    listUsers4selectorTotal,
    listUsers4selectorParams,
  } = props;

  const [searchHeight, setSearchHeight] = useState<number>(0);

  const dataSource = useMemo(() => {
    let data = listUsers4selector;
    if (props.hasOwnProperty('isActive') && props.isActive !== null && props.isActive !== undefined) {
      data = data.filter((item: any) => item.isActive === props.isActive);
    }
    return data;
  }, [listUsers4selector]);

  const fetch = useCallback(
    (params: object = {}, page: number = 0, pageSize: number = 50) => {
      dispatch({
        type: 'selectors/listUser',
        payload: { withAuth, params: { page, pageSize, ...params } },
      });
    },
    [withAuth],
  );

  const initFetch = useCallback(() => {
    fetch();
    value && value.length && setSelectedItem(value, []);
  }, [value, valueProp]);

  const handlerSelect = useCallback((rowKeys, rows) => {
    setSelectedItem(rowKeys, rows);
    onChange && onChange(rowKeys, rows);
  }, []);

  const onSearch = useCallback((params) => {
    fetch(params);
  }, []);

  //分页变化
  const onChangePage = useCallback(
    (page, pageSize) => {
      const { filterInfo } = listUsers4selectorParams;
      fetch(filterInfo, page, pageSize);
    },
    [listUsers4selectorParams],
  );

  const onSearchSizeChange = useCallback(({ height }: any) => {
    setSearchHeight(height);
  }, []);

  const _columns = useMemo(() => {
    return map(columns, (item) => {
      if (item.fieldName == 'userName') {
        return { ...item, render: (text: any, record: any) => <UserColumn id={record.id} /> };
      } else if (item.fieldName == 'userType') {
        return {
          ...item,
          valueFormatter: (params: any) => getCodeLocaleName('FW_USER_TYPE', params.value),
        };
      } else {
        return item;
      }
    });
  }, [columns]);

  const gridHei = useMemo(() => {
    const diff =
      MODAL_HEADER_HEIGHT + MODAL_PADDING_HEIGHT * 2 + MODAL_FOOTER_HEIGHT + searchHeight + BLOCK_HEADER_HEIGHT;
    if (!modalHei) return tableHei;
    const hei = modalHei - diff;
    return (hei > 0 && hei) || 'auto';
  }, [modalHei, tableHei, searchHeight]);

  useEffect(() => {
    if (typeof visible === 'boolean') {
      visible && initFetch();
    } else {
      initFetch();
    }
  }, [visible]);

  return (
    <div>
      <SearchForm
        searchKey={`user_selector:${userId}`}
        title={commonText.smartSearchTitleText}
        headerProps={{ type: 'line', bottomLine: false }}
        onSearch={onSearch}
        uiSchema={searchUISchema}
        schema={searchFormschema}
        onSizeChange={onSearchSizeChange}
      />
      <Header title={commonText.smartGridTitleText} type="line" />
      <Grid
        hideMenuItemExport
        columns={_columns}
        rowkey={valueProp}
        dataSource={dataSource}
        loading={loading}
        height={gridHei}
        rowSelection={{
          type: multiple ? 'multiple' : 'single',
          selectedKeys: selectedRowKeys,
          selectedRows,
          onSelect: handlerSelect,
        }}
        boxColumnIndex={['userLoginName', 'userName']}
        pagination={{
          total: listUsers4selectorTotal, //总条数
          beginIndex: listUsers4selectorParams.pageInfo.beginIndex, //当前页数
          pageSize: listUsers4selectorParams.pageInfo.pageSize, //每页显示数
          onChange: onChangePage,
        }}
      />
    </div>
  );
});

SelectorView.defaultProps = {
  multiple: false,
  value: [],
  valueProp: 'id',
  gridHei: 'auto',
  withAuth: false,
};

export interface ConnectProps extends SelectorPanelProps {
  viewRef: object;
}
class ConnectComp extends React.Component<ConnectProps> {
  state = {
    selectedRowKeys: [],
    selectedRows: [],
  };
  static defaultProps = {
    viewRef: {},
  };

  componentDidMount() {
    this.props.viewRef.current = this;
  }
  setSelectedItem = (selectedRowKeys: string[], selectedRows: any[]) => {
    this.setState({ selectedRowKeys, selectedRows });
  };

  getValues = () => {
    const { selectedRowKeys, selectedRows } = this.state;
    return { selectedRowKeys, selectedRows };
  };
  render() {
    const { selectedRowKeys, selectedRows } = this.state;
    return (
      <SelectorView
        {...this.props}
        selectedRowKeys={selectedRowKeys}
        selectedRows={selectedRows}
        setSelectedItem={this.setSelectedItem}
      />
    );
  }
}
export default connect(({ selectors, user, loading }: any) => ({
  loading: loading.effects['selectors/listUser'],
  userId: user.currentUser.id,
  listUsers4selector: selectors.listUsers4selector,
  listUsers4selectorTotal: selectors.listUsers4selectorTotal,
  listUsers4selectorParams: selectors.listUsers4selectorParams,
}))(ConnectComp);
